home *** CD-ROM | disk | FTP | other *** search
/ ftp.cs.arizona.edu / ftp.cs.arizona.edu.tar / ftp.cs.arizona.edu / icon / newsgrp / group98c.txt / 000143_icon-group-sender _Thu Dec 17 16:31:54 1998.msg < prev    next >
Internet Message Format  |  2000-09-20  |  2KB

  1. Return-Path: <icon-group-sender>
  2. Received: (from root@localhost)
  3.     by baskerville.CS.Arizona.EDU (8.9.1a/8.9.1) id QAA26266
  4.     for icon-group-addresses; Thu, 17 Dec 1998 16:31:48 -0700 (MST)
  5. Message-Id: <199812172331.QAA26266@baskerville.CS.Arizona.EDU>
  6. Date: Thu, 17 Dec 1998 14:21:23 -0700
  7. From: Steve Wampler <swampler@gemini.edu>
  8. X-Accept-Language: en
  9. To: icon-group@optima.CS.Arizona.EDU
  10. Subject: Re: Small Icon programming problem
  11. Errors-To: icon-group-errors@optima.CS.Arizona.EDU
  12. Status: RO
  13.  
  14. Ralph Griswold wrote:
  15. > Here's a small Icon programming problem for you to tackle:
  16. >         Write a procedure digsort(i) that returns the integer that
  17. >         results from sorting the digits of i, preserving sign.  For
  18. >         example, digsort(201) should return 12 and digsort(-1042)
  19. >         should return -124.  You may assume i is an integer.
  20. > You could aim for brevity, speed, and/or clarity.
  21. > Send solutions and comments to icon-group.  The most interesting
  22. > solutions will appear in a future issue of the Icon Analyst and
  23. > sent to icon-group as a package.
  24.  
  25. What a fun thing to play with!  Here's two more solutions. For
  26. my test cases these are the fastest I've been able to come up with.
  27. (I suspect there is a much faster approach involving map(), but
  28. this may just be a pipedream.)
  29.  
  30. The 2nd is slightly faster, but relies on the trick of returning
  31. a string that looks right (so it's hard to tell that it isn't
  32. returning an integer.)
  33.  
  34. Performance is affected by the choice of input.
  35.  
  36. procedure digsort(i)
  37.     local s, c
  38.  
  39.     s := ""
  40.     i := string(i)                              # convert to string
  41.     every c := !cset(i) do {                    # get correct order
  42.         every s ||:= (find(c,i) & c)            # get correct count
  43.         }
  44.  
  45.     return integer(s)                           # convert back to int
  46. end     
  47.  
  48. The next version is barely faster, due to a 'trick' and has an obscure bit
  49.     of code in cset(integer(cset(i))):
  50.  
  51. procedure digsort(i)
  52.     local s, c, j
  53.    
  54.     s := ""
  55.     i := string(i)                              # convert to string
  56.     every c := !cset(integer(cset(i))) do {     # get correct order & toss 0
  57.         every s ||:= (find(c,i) & c)            # get correct count
  58.         } 
  59.     
  60.     return s
  61. end 
  62.  
  63.  
  64. -- 
  65. Steve Wampler (swampler@gemini.edu)
  66.